package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
@Api(tags = "WX端地址相关操作")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @GetMapping("/list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public Result<List<AddressBook>> getAddressBook() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBooks = addressService.findAddress(addressBook);
        return Result.success(addressBooks);
    }

    @PostMapping
    @ApiOperation("新增地址")
    public Result addAddressBook(@RequestBody AddressBook address) {
        addressService.addAddress(address);
        return Result.success();
    }

    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result updateAddressBook(@RequestBody AddressBook address) {
        addressService.setDefault(address);
        return Result.success();
    }

    //修改地址，删除地址，回显地址
    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
    public Result<AddressBook> getAddressBookById(@PathVariable("id") long id) {
        AddressBook addressBook = addressService.findAddressById(id);
        return Result.success(addressBook);
    }

    @PutMapping
    @ApiOperation("根据id修改地址")
    public Result updateAddressBookById(@RequestBody AddressBook address) {
        addressService.updateById(address);
        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("删除地址")
    public Result deleteAddressBook(@RequestBody AddressBook address) {
        addressService.deleteAddress(address);
        return Result.success();
    }


    @GetMapping("/default")
    @ApiOperation("查询当默认地址--在用户下单的时候在下单页面")
    public Result<AddressBook> getDefault() {
        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(1);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressService.findAddress(addressBook);

        if (list != null && list.size() == 1) {
            return Result.success(list.get(0));
        }

        return Result.error("没有查询到默认地址");
    }

}
